package gob.osinerg.emergencia.action;

import gob.osinerg.emergencia.bean.ActividadBean;
import gob.osinerg.emergencia.bean.FormularioEmergenciaUnmay;
import gob.osinerg.emergencia.bean.Incidente;
import gob.osinerg.emergencia.bean.IncidenteAccionCorrectiva;
import gob.osinerg.emergencia.bean.IncidenteDetalle;
import gob.osinerg.emergencia.bean.UnidadOperativaBean;
import gob.osinerg.emergencia.bean.UsuarioBean;
import gob.osinerg.emergencia.form.IncidenteForm;
import gob.osinerg.emergencia.service.GenericService;
import gob.osinerg.emergencia.service.IncidenteService;
import gob.osinerg.emergencia.util.Report;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.util.ResourceUtils;

public class IncidenteAction extends GenericAction {

	private Log log = LogFactory.getLog(IncidenteAction.class);

	private IncidenteService service;
	private GenericService genericService;

	public ActionForward inicio(ActionMapping actionMapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws java.lang.Exception {

		IncidenteForm form = (IncidenteForm) actionForm;
		form.setBean(new Incidente());
		form.getMapList().put("anioList",
				gob.osinerg.emergencia.util.Converter.getListaAnnos());
		form.getMapList().put("mesList",
				gob.osinerg.emergencia.util.Converter.getListaMeses());
		form.setDetalleList(new ArrayList());
		form.getDetalleList().add(new IncidenteDetalle());

		return actionMapping.findForward("inicio");
	}

//	public ActionForward getIncidenteDetalle(ActionMapping actionMapping,
//			ActionForm actionForm, HttpServletRequest request,
//			HttpServletResponse response) throws java.lang.Exception {
//
//		IncidenteForm form = (IncidenteForm) actionForm;
//
//		HttpSession session = request.getSession();
//		
//		UnidadOperativaBean unidadOperativa = (UnidadOperativaBean) session
//				.getAttribute("UnidadOperativaBean");		
//		
//		Incidente bean = (Incidente) form.getBean();
//		
//		Incidente incidente = new Incidente();
//		incidente.setAnio(bean.getAnio());
//		incidente.setMes(bean.getMes());
//		incidente.setIdUnidadOperativa(Long.valueOf(unidadOperativa.getCodigo()));
//		
//		List list = genericService.getFindCriteria(incidente);
//		
//		if(!list.isEmpty()){
//			form.setBean(list.get(0));
//			Long idIncidente = ((Incidente)(list.get(0))).getId();
//			IncidenteDetalle detalle = new IncidenteDetalle();
//			detalle.setIdIncidente(idIncidente);
//			form.setDetalleList(genericService.getFindCriteria(detalle)); 
//		}else{
//
//			form.setBean(incidente);
//			form.setDetalleList(new ArrayList()); 
//			form.getDetalleList().add(new IncidenteDetalle());
//		}
//
//		return actionMapping.findForward("inicio");
//	}	

	public ActionForward doSave(ActionMapping actionMapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws java.lang.Exception {
		Date fechaActual = new Date();
		SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
		String cadenaFecha = formato.format(fechaActual);
		IncidenteForm form = (IncidenteForm) actionForm;
		FormularioEmergenciaUnmay beanform = new FormularioEmergenciaUnmay();
		String message = "messages.insert.successful";
		try {
			Incidente bean = (Incidente) form.getBean();

			HttpSession session = request.getSession();
			UnidadOperativaBean unidadOperativa = (UnidadOperativaBean) session
					.getAttribute("UnidadOperativaBean");
			
			UsuarioBean usuario = (UsuarioBean) session.getAttribute("UsuarioBean");

			ActividadBean actividad=(ActividadBean)session.getAttribute("ActividadBean");

			Long idUnidadOperativa = Long.valueOf(unidadOperativa.getCodigo());
			
			beanform.setUniopeId(idUnidadOperativa);
			beanform.setCdgoOsinerg(unidadOperativa.getCodigoOsinerg());
			beanform.setRegistroDgh(unidadOperativa.getCodigoDGH());
			beanform.setFrmlarioId(new Long(8));
			beanform.setTpoEmrgncia("IDP");
			beanform.setEstado("GE");
			beanform.setMdioInfrmtvo("SEM");
			beanform.setActiviId(new Long(actividad.getCodigo()));
			beanform.setStrFecha(cadenaFecha);
			beanform.setUsrioCrdor(usuario.getCodigoLogin());
			beanform.setFchaCrcion(new Date());
			
			bean.setIdUnidadOperativa(idUnidadOperativa);
			bean.setUsrioCrdor(usuario.getCodigoLogin());
			bean.setFchaCrcion(new Date());
			
			//Fabriccio - 13/06/2011 - INICIO
			form.setAnio(bean.getAnio());
			form.setMes(bean.getMes());
			//Fabriccio - 13/06/2011 - FIN
			
			service.save(bean, form.getDetalleList(), beanform);
			sendSuccessfulMessage(request, message);
		} catch (Exception ex) {
			log.error(ex.getMessage());
			ex.printStackTrace();
			message = "errors.update.failed.finalParam";
			throw new Exception(ex.getMessage());
		}

		return actionMapping.findForward("inicio");
	}

	public ActionForward doAddDetalle(ActionMapping actionMapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws java.lang.Exception {

		IncidenteForm form = (IncidenteForm) actionForm;
		form.getDetalleList().add(new IncidenteDetalle());

		return actionMapping.findForward("inicio");
	}

	public ActionForward doSearchAccionCorrectiva(ActionMapping actionMapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws java.lang.Exception {

		IncidenteForm form = (IncidenteForm) actionForm;

		int indexDetalle = Integer.valueOf(request.getParameter("indexIncidenteDetalle")).intValue();
		form.setIndexIncidenteDetalle(indexDetalle);
		
		Incidente bean = (Incidente) form.getBean();
		List detalleList = form.getDetalleList();
		IncidenteDetalle detalle = (IncidenteDetalle) detalleList.get(indexDetalle);
		
		List accionCorrectivaList = new ArrayList();
		if(bean.getId() == null){
	
			if( detalle.getAccionCorrectivaList() == null){
				accionCorrectivaList.add(new IncidenteAccionCorrectiva());	
			}else{
				accionCorrectivaList = detalle.getAccionCorrectivaList();
			}
		}else{
			if(detalle.getAccionCorrectivaList() == null){
				IncidenteAccionCorrectiva accionCorrectiva = new IncidenteAccionCorrectiva();
				accionCorrectiva.setIdIncidenteDetalle(detalle.getId());
				accionCorrectivaList = genericService.getFindCriteria(accionCorrectiva);				
			}else{
				accionCorrectivaList = detalle.getAccionCorrectivaList();
			}
		}
		form.setAccionCorrectivaList(accionCorrectivaList);

		return actionMapping.findForward("accionCorrectiva");
	}
	
	public ActionForward doAddAccionCorrectiva(ActionMapping actionMapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws java.lang.Exception {

		IncidenteForm form = (IncidenteForm) actionForm;
		form.getAccionCorrectivaList().add(new IncidenteAccionCorrectiva());

		return actionMapping.findForward("accionCorrectiva");
	}	
	
	public ActionForward doSaveAccionCorrectiva(ActionMapping actionMapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws java.lang.Exception {

		IncidenteForm form = (IncidenteForm) actionForm;
		
		int index = form.getIndexIncidenteDetalle();
		List accionCorrectivaList = form.getAccionCorrectivaList();
		((IncidenteDetalle) (form
				.getDetalleList().get(index))).setAccionCorrectivaList(accionCorrectivaList);
		
		return actionMapping.findForward("inicio");
	}
	
	public ActionForward doDeleteDetalle(ActionMapping actionMapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws java.lang.Exception {

		IncidenteForm form = (IncidenteForm) actionForm;

		int indexDetalle = Integer.valueOf(request.getParameter("indexIncidenteDetalle")).intValue();
		List detalleList = form.getDetalleList();
		if(detalleList.size() > 1){
			detalleList.remove(indexDetalle);
		}
		return actionMapping.findForward("inicio");
	}	
	
//	public ActionForward doDeleteAccionCorrectiva(ActionMapping actionMapping,
//			ActionForm actionForm, HttpServletRequest request,
//			HttpServletResponse response) throws java.lang.Exception {
//
//		IncidenteForm form = (IncidenteForm) actionForm;
//
//		int indexDetalle = form.getIndexIncidenteDetalle();
//		int indexAccionCorrectiva = Integer.valueOf(request.getParameter("indexAccionCorrectiva")).intValue();
//		
//		System.out.println("indexDetalle: " + indexDetalle + "    indexAccionCorrectiva: " + indexAccionCorrectiva);
//		
//		List detalleList = form.getDetalleList();
//		List accionCorrectivaList = ((IncidenteDetalle)detalleList.get(indexDetalle)).getAccionCorrectivaList();
//		if(accionCorrectivaList.size() > 1){
//			detalleList.remove(indexAccionCorrectiva);
//		}		
//		
//		return actionMapping.findForward("inicio");
//	}	
	
    public ActionForward exportar(ActionMapping mapping, ActionForm actionForm,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
    	
    	IncidenteForm form = (IncidenteForm)actionForm;

    	try{
            request.setAttribute("actionReport","reporteAccidenteLeve.do");
            
            HttpSession session = request.getSession();
    		UnidadOperativaBean unidadOperativa = (UnidadOperativaBean) session
    				.getAttribute("UnidadOperativaBean");

    		Long idUnidadOperativa = Long.valueOf(unidadOperativa.getCodigo());        
    		String anio = (form.getAnio().toString()).equals("0") ? null : form.getAnio().toString();
    		String mes = (form.getMes().toString()).equals("0") ? null : form.getMes().toString();
    		String formatoReporte = request.getParameter("formatoReporte");

            Map parameters = new HashMap();
            parameters.put("UNIOPE_ID", idUnidadOperativa.toString());
            parameters.put("ANIO", anio);
            parameters.put("MES", mes);
            parameters.put("REGISTRO_DGH", unidadOperativa.getCodigoDGH());            
            parameters.put("IMAGE_LOGO", request.getRequestURL().substring(0, request.getRequestURL().lastIndexOf("/"))+"/images/logo_home.jpg");

            File archivo = ResourceUtils.getFile("classpath:gob/osinerg/emergencia/resource/jrxml/ReporteIncidente.jrxml");

    		Report report = new Report();
    		report.setJasperReport(archivo);
    		report.setParameter(parameters);
    		report.setConnection(genericService.getConnection());
    		
    		if(formatoReporte.equals("PDF")){
			report.PDF(request, response);   		
    		}else{
            	response.setHeader("Content-Disposition", "inline; filename=ReporteIncidentes.xls");
            	report.XLS(request, response, Boolean.TRUE);      			
    		}
			   		
    	}catch(Exception ex){
    		log.error(ex.getMessage());
    	}
        return null;
    }		
	
	
	public void setGenericService(GenericService genericService) {
		this.genericService = genericService;
	}

	public void setService(IncidenteService service) {
		this.service = service;
	}

}
